#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2021-12-30 10:03:23
# @Author  : khz_mac
# @Site    :
# @File    : __init__.py.py
# @Software: ce9nt

"""
源码来自CSDN博主“挣扎的蓝藻”，已授权了。
博主网站地址：https://lanzao.blog.csdn.net/
源码文章地址：https://lanzao.blog.csdn.net/article/details/121072025

J:\_ALL\CODE\venv\py386_automate\Scripts\python.exe .\auto_shipinhao.py      eyJqSWQiOiAiNzAyMTEyNDkzMzM2NzM4NTM0NiIsICJteVRpdGxlQ24iOiAiXHU1YzBmXHU2MTY3XHU1NDFiXHU4ZDg1XHU1ZjNhY29zIFx1NjYyZlx1NTkyOVx1NGY3Zlx1NTU5NH5+fiIsICJteVRhZ3NDbiI6ICIjY29zcGxheSAjXHU1YzBmXHU1OWQwXHU1OWQwICNcdTVjMGZcdTYxNjdcdTU0MWIifQ==

"""


import os
import sys
import time
import random
import datetime
import base64
import types
import json
import pathlib
import selenium
from selenium.webdriver.common import keys, by
from selenium.webdriver.support import ui, expected_conditions


def deal_desc(driver, title, lst_tags):
    """

    :param title:
    :param driver:
    :param lst_tags:
    :return:
    """
    # driver.find_element_by_xpath('//div[@aria-autocomplete="list"]//br').send_keys(param.get_title() + " #上热门 # #我要上热门")
    # ele_desc = driver.find_element_by_xpath('//div[@aria-autocomplete="list"]//br')
    # 输入标题（获取data-offset-key="3cpke-0-0"）
    ele_desc = ui.WebDriverWait(driver, 2 * 60).until(
        expected_conditions.presence_of_element_located((by.By.XPATH, '//div[@aria-autocomplete="list"]//br'))
    )
    ele_desc_root = ele_desc.find_element_by_xpath('../..')
    ele_desc.send_keys(title)
    offset_key = ele_desc_root.get_attribute('data-offset-key').split('-')[0]
    html_fmt = """
    <span class="mention--1ZCbm" spellcheck="false">
        <span data-offset-key="{0}-1-0">
            <span data-text="true">
                #美女
            </span>
        </span>
    </span>
    <span data-offset-key="{0}-2-0">
        <span data-text="true">
        </span>
    </span>
    <span class="mention--1ZCbm" spellcheck="false">
        <span data-offset-key="{0}-3-0">
            <span data-text="true">
                #cosplay
            </span>
        </span>
    </span>
    <span data-offset-key="{0}-4-0">
        <span data-text="true">
        </span>
    </span>
    """
    html = html_fmt.format(offset_key).replace('\n', '')
    driver.execute_script("""var ele=arguments[0]; ele.innerHTML = '{}';""".format(html), ele_desc_root)

    # ele_desc.send_keys(param.get_title())
    # time.sleep(1)
    #
    # # 输入标签
    # for tag in lst_tags:
    #     # == 发送 #
    #     # == 发送 $tag
    #     # == 发送 回车
    #     ele_desc.send_keys('#')
    #     time.sleep(0.5)
    #     ele_desc.send_keys(tag)
    #     time.sleep(3.5)
    #     ele_desc.send_keys(Keys.ENTER)
    #     time.sleep(1.5)


def publish(param):
    """
    作用：发布视频
    """
    options = selenium.webdriver.ChromeOptions()
    options.add_argument(r'--user-data-dir=J:\\_ALL\\chrome--user-data-dir\\公众号\\浏览器登录\\20000-爬虫分析')
    # didable "Chrome is being controled by an automated test software"
    options.add_argument('disable-infobars')
    driver = selenium.webdriver.Chrome(executable_path=r'J:\_ALL\CODE\venv\py386_automate\Scripts\chromedriver.exe', options=options)
    driver.implicitly_wait(5)

    # 进入抖音创作者页面
    # https://creator.douyin.com/creator-micro/content/upload
    driver.get("https://creator.douyin.com/creator-micro/content/publish")

    # 并上传视频
    driver.find_element_by_xpath('//input[@type="file"]').send_keys(param.get_path_video())

    # 等待视频上传完成
    # 检查一：等待视频上传完成
    # ui.WebDriverWait(driver, 2 * 60).until(
    #     expected_conditions.presence_of_element_located((by.By.CLASS_NAME, 'semi-icons-upload'))
    # )
    # ui.WebDriverWait(driver, 2 * 60).until(
    #     expected_conditions.text_to_be_present_in_element((by.By.CLASS_NAME, 'preview-box'), 'ACG美女cosplay福利')
    # )
    # print("视频已上传完成！")
    # time.sleep(5)
    # 方案一：等待元素《编辑封面》的属性从“mycard-info-text-disable--17_v5”变为“mycard-info-text-span--3Tyja”、“mycard-info-text--2DMKT”。
    while True:
        ele = driver.find_element_by_xpath('//*[text()="支持完整视频封面截取"]/following-sibling::span/span')
        if ele.get_attribute('class').find('mycard-info-text-disable') == -1:
            break
    # 方案二：支持完整视频封面截取的哥哥节点不再是img，也就是说，img节点消失的时候，上传完成。
    # 方案三：支持完整视频封面截取的哥哥节点不再是img，也就是说，img节点消失的时候，div出现的时候，上传完成。
    # ui.WebDriverWait(driver, 2 * 60).until(
    #     expected_conditions.presence_of_element_located((by.By.XPATH, '//*[text()="支持完整视频封面截取"]/preceding-sibling::div'))
    # )
    # time.sleep(3)

    # 添加封面
    driver.find_element_by_xpath('//*[text()="编辑封面"]').click()
    time.sleep(1)
    driver.find_element_by_xpath('//div[text()="上传封面"]').click()
    time.sleep(1)
    driver.find_element_by_xpath('//input[@type="file"]').send_keys(param.get_path_cover())
    time.sleep(3)
    driver.find_element_by_xpath('//*[text()="裁剪封面"]/..//*[text()="确定"]').click()
    time.sleep(3)
    driver.find_element_by_xpath('//*[text()="设置封面"]/..//*[contains(@class,"upload")]//*[text()="确定"]').click()
    time.sleep(5)

    # 输入视频描述
    lst_tags = param.get_tags_list()
    lst_tags.extend(
        random.choices(['上热门', 'dou上热门', '我要上热门'])
    )
    deal_desc(driver, param.get_title(), lst_tags)

    # 设置选项
    if False:
        time.sleep(1)
        driver.find_element_by_xpath('//*[@class="radio--4Gpx6"]').click()
        time.sleep(1)
        driver.find_element_by_xpath('//*[@class="semi-select-selection"]//span[contains(text(),"输入")]').click()
        time.sleep(1)
        driver.find_element_by_xpath('//*[@class="semi-select-selection"]//input').send_keys("中关村人工智能科技")
        time.sleep(1)
        driver.find_element_by_xpath('//*[@class="semi-select-selection"]//input').send_keys("园")
        time.sleep(5)
        driver.find_element_by_xpath('//*[@class="semi-popover-content"]//*[text()="中关村人工智能科技园"]').click()

    # 设置合辑
    eles = driver.find_elements_by_class_name('semi-select-single')
    if len(eles):
        eles[-1].click()
        time.sleep(1)
        eles = driver.find_elements_by_class_name('semi-select-option')
        if len(eles):
            eles[-1].click()

    # 同步到西瓜视频
    if False:
        time.sleep(1)
        # driver.find_element_by_xpath('//div[@class="preview--27Xrt"]//input').click()   # 默认启用一次后，后面默认启用了。
        time.sleep(1)
        driver.find_element_by_xpath('//*[@class="card-pen--2P8rh"]').click()
        time.sleep(1)
        driver.find_element_by_xpath('//*[@class="DraftEditor-root"]//br').send_keys(describe + " #上热门")
        time.sleep(1)
        driver.find_element_by_xpath('//button[text()="确定"]').click()

    # 设置发布时间
    ele = driver.find_element_by_xpath('//*[text()="定时发布"]')
    driver.execute_script("arguments[0].click();", ele)
    time.sleep(1)
    str_fabu_time = datetime.datetime.now().strftime('%Y-%m-%d 18:18')
    ele = driver.find_element_by_xpath('//*[@class="semi-datepicker-input"]//input')
    driver.execute_script("""var ele=arguments[0]; ele.value = '{}';""".format(str_fabu_time), ele)

    # # 点击发布
    # driver.find_element_by_xpath('//*[text()="发表"]').click()

    # 等待发布完成
    # time.sleep(5 * 60)
    for i in range(3 * 60):
        if 'https://creator.douyin.com/creator-micro/content/manage' in driver.current_url:  # 新的页面url包含某个字符
            break
        time.sleep(1)
    time.sleep(5)

    return 0


class VideoParam:
    """
    从java后台传过来的视频参数
        param_j         {"jId": "7021124933367385346", "myTitleCn": "小慧君超强cos 是天使喔~~~", "myTagsCn": "#cosplay #小姐姐 #小慧君"}
                        {"jId": "7021124933367385346", "myTitleCn": "\u5c0f\u6167\u541b\u8d85\u5f3acos \u662f\u5929\u4f7f\u5594~~~", "myTagsCn": "#cosplay #\u5c0f\u59d0\u59d0 #\u5c0f\u6167\u541b"}
        param_b64       eyJqSWQiOiAiNzAyMTEyNDkzMzM2NzM4NTM0NiIsICJteVRpdGxlQ24iOiAiXHU1YzBmXHU2MTY3XHU1NDFiXHU4ZDg1XHU1ZjNhY29zIFx1NjYyZlx1NTkyOVx1NGY3Zlx1NTU5NH5+fiIsICJteVRhZ3NDbiI6ICIjY29zcGxheSAjXHU1YzBmXHU1OWQwXHU1OWQwICNcdTVjMGZcdTYxNjdcdTU0MWIifQ==
    """
    def __init__(self, param_b64):
        # base64解密
        param_j = json.loads(base64.b64decode(param_b64))
        print(param_j)

        # 解析参数
        self.param = types.SimpleNamespace(**param_j)

        self.path_root = r'J:/_ALL/CODE/gitee/constellations/pig-ui/public/_tiktok_res/'

    def get_title(self):
        return self.param.myTitleCn

    def get_tags(self):
        return self.param.myTagsCn

    def get_tags_list(self):
        """

        :return: ['cosplay', '小姐姐', '小慧君']
        """
        lst = []
        for tag in self.param.myTagsCn.split('#'):
            tag = tag.strip()
            if len(tag) == 0:
                continue

            lst.append(tag)

        return lst

    def get_path_video(self):
        return '{}video/{}.mp4'.format(self.path_root, self.param.jId)

    def get_path_cover(self):
        return '{}cover/{}.jpg'.format(self.path_root, self.param.jId)


def main():
    # 处理参数
    if len(sys.argv) < 2:
        print('len(sys.argv) < 2')
        return 1

    param = VideoParam(sys.argv[1])
    print(param.get_title(), param.get_path_video(), param.get_path_cover())
    print('get_tags_list()', param.get_tags_list())

    # 开始执行视频发布
    return publish(param)


if __name__ == "__main__":
    print("------------------    Enter __main__    ------------------")

    print(u"[Current work directory is : ]\t" + os.getcwd())
    print(u"[Current process ID is : ]\t" + str(os.getpid()))
    print("\n")
    ret = main()

    print("------------------    Leave __main__    ------------------")

    exit(ret)
